import http from '@ohos.net.http'
import {AppResult} from '../bean/AppReslt'
import {ListBean} from'../bean/ListBean'
import { BannerBean } from '../bean/BannerBean'
import { MyTag } from '../bean/MyTag'
import { NavBean } from '../bean/NavBean'
import { LoginBean } from '../bean/LoginBean'
import Prompt from '@system.prompt'

//定义基准路径
export let  baseUrl = "https://www.wanandroid.com/"
// 每一个httpRequest对应一个HTTP请求任务，不可复用
export  let httpRequest = http.createHttp();

export function register(option) : Promise<AppResult<LoginBean>>{
  return  baseHttp<LoginBean>(option)
}

export function login(option) : Promise<AppResult<LoginBean>>{
  return  baseHttp<LoginBean>(option)
}

export function getNavTags(option) : Promise<AppResult<NavBean[]>>{
  return  baseHttp<NavBean[]>(option)
}

export function getTags(option) : Promise<AppResult<MyTag[]>>{
  return  baseHttp<MyTag[]>(option)
}

export function getCollect(option) : Promise<AppResult<String>>{
  return  baseHttp<String>(option)
}

export function getHomeBannerData(option) : Promise<AppResult<BannerBean[]>>{
  return  baseHttp<BannerBean[]>(option)
}

export function getHomeTopData(option) : Promise<AppResult<ListBean>>{
  return  baseHttp<ListBean>(option)
}

export function getHomeData(option) : Promise<AppResult<ListBean>>{
  return  baseHttp<ListBean>(option)
}


function baseHttp<T>(option):Promise<AppResult<T>>{
  let url = baseUrl + option.url
  return  new Promise((resolve,reject) =>{
    httpRequest.request(url,{
      method:  option.method || http.RequestMethod.GET,
      extraData:option.data || {}
    }).then(resp =>{
      if(resp.responseCode == 200){
        console.log("baseHttp","相应结果: "+JSON.stringify(resp.result))
        let res:AppResult<T> = JSON.parse(resp.result.toString())
        if(res.errorCode == 0){
          resolve(res)
        }else{
          Prompt.showToast({
            message:"请求失败: "+res.errorMsg,
            duration:1000,
          })
        }
      }else{
        Prompt.showToast({
             message:"请求失败: "+JSON.stringify(resp),
             duration:1000,
        })
      }
    }).catch (err =>{
       reject("请求异常: "+JSON.stringify(err))
       Prompt.showToast({
        message:"请求异常: "+JSON.stringify(err),
        duration:1000,
      })
    })
  })
}
